import { ReActAgent } from "../../../ch08/ReAct-agent";
import { MultiAgentSystem } from "../../../ch10/ceshi";
import { NextRequest } from "next/server";

// 单例模式：复用 Agent 实例，避免重复创建
let reactAgentInstance: ReActAgent | null = null;
let multiAgentInstance: MultiAgentSystem | null = null;

// 当首次调用时，创建 Agent 实例并缓存；后续调用直接返回已缓存的实例，确保全局只有一个 Agent 实例在运行。
function getReActAgent() {
  if (!reactAgentInstance) {
    reactAgentInstance = new ReActAgent();
  }
  return reactAgentInstance;
}

function getMultiAgent() {
  if (!multiAgentInstance) {
    multiAgentInstance = new MultiAgentSystem();
  }
  return multiAgentInstance;
}

// 请求验证
// 验证前端传入的参数合法性，避免无效请求进入业务逻辑
function validateRequest(message: string, agentType: string) {
  if (!message || typeof message !== 'string') {
    throw new Error("消息内容不能为空");
  }
  
  if (message.length > 1000) {
    throw new Error("消息长度不能超过 1000 字符");
  }
  
  if (!['react', 'multi'].includes(agentType)) {
    throw new Error("不支持的 Agent 类型");
  }
}

// 设置超时
// 超时控制函数
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
  return Promise.race([
    promise,
    new Promise<T>((_, reject) =>
      setTimeout(() => reject(new Error(`请求超时（${timeoutMs / 1000}秒）`)), timeoutMs)
    )
  ]);
}

export async function POST(req: NextRequest) {
  try {
    // 解析请求体
    const { message, agentType = "react", stream = false } = await req.json();
    
    // 验证请求
    validateRequest(message, agentType);
    
    console.log(`📨 收到请求 [${agentType}${stream ? ' - 流式' : ''}]: ${message.substring(0, 50)}...`);
    
    // 如果请求流式输出
    if (stream && agentType === "react") {
      const encoder = new TextEncoder();
      const customReadable = new ReadableStream({
        async start(controller) {
          try {
            const agent = getReActAgent();
            
            // 执行 Agent，使用流式回调实时发送 LLM 生成的内容
            const result = await agent.run(message, (chunk: string) => {
              // 实时发送 LLM 生成的每个文本片段
              controller.enqueue(encoder.encode(chunk));
            });
            
            // 发送分隔符和完成标记
            controller.enqueue(encoder.encode('\n\n---DONE---\n\n'));
            controller.close();
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : "未知错误";
            controller.enqueue(encoder.encode(`\n\n---ERROR: ${errorMessage}---\n\n`));
            controller.close();
          }
        }
      });
      
      return new Response(customReadable, {
        headers: {
          'Content-Type': 'text/plain; charset=utf-8',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
        },
      });
    }
    
    // 非流式输出（原有逻辑）
    let result;
    
    // 根据 Agent 类型调用对应逻辑
    if (agentType === "react") {
      const agent = getReActAgent();
      // 设置 60 秒超时
      result = await withTimeout(agent.run(message), 60000);
      
      // 验证 ReActAgent 返回结果
      if (!Array.isArray(result) || result.length === 0) {
        throw new Error("ReActAgent 返回了无效的结果：期望 AgentState[] 数组");
      }
    } else if (agentType === "multi") {
      const system = getMultiAgent();
      // Multi-Agent 需要更长时间，设置 120 秒超时
      result = await withTimeout(system.collaborate(message), 120000);
      
      // 验证 MultiAgentSystem 返回结果
      if (!result || typeof result !== 'object' || !('final_answer' in result)) {
        throw new Error("MultiAgentSystem 返回了无效的结果：期望 CollaborateResult 对象");
      }
    }
    
    console.log(`✅ 请求完成 [${agentType}]`);
    
    return Response.json({ 
      success: true, 
      data: result,
      agentType 
    });
    
  } catch (error: unknown) {
    console.error("❌ API 错误:", error);
    
    const errorMessage = error instanceof Error ? error.message : "未知错误";
    const statusCode = errorMessage.includes("超时") ? 504 : 500;
    
    return Response.json({ 
      success: false,
      error: errorMessage,
      timestamp: new Date().toISOString()
    }, { 
      status: statusCode 
    });
  }
}

// 可选：添加 GET 方法用于健康检查
export async function GET() {
  return Response.json({ 
    status: "ok",
    agents: {
      react: reactAgentInstance !== null,
      multi: multiAgentInstance !== null
    }
  });
}
